package com.example.zjx8969.myapplication

import android.media.MediaPlayer
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ViewModel

class MediaPlayerPool : ViewModel(), LifecycleObserver {
    private var playingIndex = -1
    private val mediaPlayersInUse = ArrayList<MediaPlayer>(4)

    private val mediaPlayerCache = java.util.ArrayDeque<MediaPlayer>(2)
    var count = 0

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun releaseAll() {
        mediaPlayerCache.forEach {
            it.release()
        }

        mediaPlayersInUse.forEach {
            it.release()
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun pauseActiveMediaPlayer() {
        mediaPlayersInUse.forEachIndexed { index, mediaPlayer ->
            if (mediaPlayer.isPlaying) {
                mediaPlayer.pause()
                playingIndex = index
            }
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun resumePlayStatus() {
        mediaPlayersInUse.forEachIndexed { index, mediaPlayer ->
            if (playingIndex == index) {
                mediaPlayer.start()
            }
        }
    }

    fun getMediaPlayer(): MediaPlayer {
        var firstOrNull = mediaPlayerCache.pollFirst()
        if (firstOrNull == null) {
            count++
            firstOrNull = MediaPlayer()
        }
        Log.e("tag", "mediaCount:$count")
        firstOrNull.setScreenOnWhilePlaying(true)
        firstOrNull.setVolume(1f, 1f)
        return firstOrNull
    }

    fun markInUse(mediaPlayer: MediaPlayer) {
        mediaPlayersInUse.add(mediaPlayer)
    }

    fun recycle(mediaPlayer: MediaPlayer) {
        mediaPlayer.reset()
        mediaPlayersInUse.remove(mediaPlayer)
        mediaPlayerCache.add(mediaPlayer)
    }

}